package LeetCode;

import java.util.ArrayList;
import java.util.List;

public class LC_057_InsertInterval {
    public static void main(String[] args) {

    }

    static class Interval {
        int start;
        int end;

        Interval() {
            start = 0;
            end = 0;
        }

        Interval(int s, int e) {
            start = s;
            end = e;
        }
    }

    static class Solution {

        public List<Interval> insert(List<Interval> intervals, Interval newInterval) {

            if (newInterval == null)
                return intervals;
            int len = intervals.size();

            if (len == 0) {
                intervals.add(newInterval);
                return intervals;
            }

            List<Interval> res = new ArrayList<>();

            for (Interval interval : intervals) {
                if (interval.end < newInterval.start)
                    res.add(interval);
                else if (interval.start > newInterval.end) {
                    res.add(newInterval);
                    newInterval = interval;
                } else if (interval.start <= newInterval.end || interval.end >= newInterval.start)
                    newInterval = new Interval(Math.min(interval.start, newInterval.start), Math.max(interval.end, newInterval.end));
            }
            
            res.add(newInterval);
            return res;
        }

    }

}
